var express = require("express");
var app = express();
var query = require('./congif/db');
const cors = require('cors')

// 接收Post请求的参数
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.use(cors())
//根据参数，查询数据
app.get('/books', async (req, res) => {
	//查询语句
	let sql = `select * from book`;
	let data = await query(sql)
	res.json(data)
})
//增加数据
app.post('/add', async (req, res) => {
	let { book_name, book_author, book_desc } = req.body.goodsInfo
	let sql = `insert into book (books_name,books_author,books_desc)value('${book_name}','${book_author}','${book_desc}')`
	let result = await query(sql)
	if (result.affectedRows) {
		res.json({ code: 10000, message: '添加成功' })
	} else {
		res.json({ code: 10001, message: '添加失败' })
	}
});
//修改数据
app.post('/editBtn', async (req, res) => {
	//处理请求修改的数据和条件
	let { id } = req.body;
	let sql = `select * from book where id = ${id}`;
	let data = await query(sql);
	res.json(data)
});

app.post('/update', async (req, res) => {
	let { id, book_name, book_author, book_desc } = req.body.goodsData
	let sql = `update book set books_name = '${book_name}',books_author='${book_author}',books_desc = '${book_desc}'
	 where id=${id}`
	let result = await query(sql)
	if (result.affectedRows) {
		res.json({ code: 10004, message: '更新成功' })
	} else {
		res.json({ code: 10005, message: '更新失败' })
	}
})
//删除数据
app.post('/delete', async (req, res) => {
	let { id } = req.body;
	let sql = `delete from book where id = ${id}`
	let result = await query(sql)

	if (result.affectedRows) {
		res.json({ code: 10002, message: '删除成功' })
	} else {
		res.json({ code: 10003, message: '删除失败' })
	}
})
//关闭连接 
//connection.end();
//监听8080端口
app.listen(8080, function () {
	console.log('server running at 8080 port')
})